﻿using com.lythen.file.Security.Entities;
using System.Data.SQLite;
using System.IO;

namespace com.lythen.file.Security.Configuration
{
    /***************************************************************************
     * CLR版本：4.0.30319.42000
     *唯一标识：e86761c2-9241-4501-9150-20567abe7ad8
     *  创建人：赖仁良
     *创建时间：2024/1/2 11:39:28
     *功能描述：
     * ----------------------------------------------------------------
     * 修改人：
     * 时间：
     * 修改说明：
     *=========================================================================*/
    /// <summary>
    /// 
    /// </summary>
    class DbHelper
    {
        public static void CheckDbFile()
        {
            string dbFile = "./data/data.db";
            if (File.Exists(dbFile))
            {
                return;
            }
            InitDbFile(dbFile);
        }
        private static void InitDbFile(string dbFile)
        {
            string password = "Lythen@163.com";
            string connectionString = $"Data Source={dbFile};Version=3;";

            string folder = Path.GetDirectoryName(dbFile);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            string createTableQuery = "CREATE TABLE IF NOT EXISTS MyTable (Id INTEGER PRIMARY KEY, Name TEXT);";

            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(connection))
                {

                    command.CommandText = createTableQuery;
                    command.ExecuteNonQuery();
                }
            }
            // 使用 ATTACH DATABASE 命令附加加密数据库
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // ATTACH DATABASE SQL 语句
                string attachDatabaseQuery = $"ATTACH DATABASE '{dbFile}' AS encrypted KEY '{password}';";

                using (var command = new SQLiteCommand(attachDatabaseQuery, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
            using (var db = new LythenContext())
            {
                //增
                db.UserKeysSet.Add(new UserKeys() { UserName = "admin", PublicKey = "11", PrivateKey = "12" });
                db.SaveChanges();
            }
        }
    }
}
